package com.sicheng.algorithm.node;

public class ListNode {
    public int val;
    public ListNode next;

    public ListNode random;

    public ListNode(int val) {
        this.val = val;
    }

    @Override
    public String toString() {
        return "ListNode{" +
                "data=" + val +
                '}';
    }

    public static void list(ListNode head) {
        if (head == null)
            return;

        while (head.next != null) {
            System.out.println(head);
            head = head.next;
        }
        System.out.println(head);
    }

    public static ListNode initList(int[] data) {
        if (data == null || data.length == 0) {
            return null;
        }

        ListNode head = new ListNode(data[0]);
        if (data.length >= 2) {
            for (int i = 1; i < data.length; i++) {
                ListNode node = new ListNode(data[i]);
                insertOnTail(head, node);
            }

        }
        return head;
    }

    public static ListNode getTail(ListNode head) {
        if (head == null)
            return null;

        while (head.next != null)
            head = head.next;

        return head;
    }


    public static void insertOnTail(ListNode head, ListNode node) {
        if (head == null || node == null)
            return;

        ListNode temp = head;
        while (temp.next != null) {
            temp = temp.next;
        }

        temp.next = node;

    }
}
